/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cgbsoft.financial.charts;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.cgbsoft.financial.R;
import com.cgbsoft.financial.domain.MyTransaction;
import com.cgbsoft.financial.utils.DateUtil;
import com.cgbsoft.financial.utils.StringUtils;

/**
 * Average temperature demo chart.
 */
public class SpendMoneyLineChartActivity extends AbstractChart implements OnClickListener {

	private static List<MyTransaction> totalTransactionList = new ArrayList<MyTransaction>();
	
	private static List<MyTransaction> showTransactionList = new ArrayList<MyTransaction>();
	
	private static Map<String, List<MyTransaction>> showTransactionByMonthMap = new HashMap<String, List<MyTransaction>>();
	
	private static Map<String, BigDecimal> showDaySpendMap = new HashMap<String, BigDecimal>();
	
	private static Map<String, BigDecimal> showMonthSpendMap = new HashMap<String, BigDecimal>();
	
	private Button preMonth, currentMonth, nextMonth;
	
	//搜索开始日期
	private String dateStart = ""; 
	//搜索结束日期
	private String dateEnd = ""; 
	
	/**
	 * Executes the chart demo.
	 * 
	 * @param context
	 *            the context
	 * @return the built intent
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chart_spend_money);
        
        preMonth = (Button) findViewById(R.id.preMonth);
        currentMonth = (Button) findViewById(R.id.currentMonth);
        nextMonth = (Button) findViewById(R.id.nextMonth);
        nextMonth.setEnabled(false);//一开始没有下一年
        
        preMonth.setOnClickListener(this);
        currentMonth.setOnClickListener(this);
        nextMonth.setOnClickListener(this);
        
        
        showTransactionList = getCurrentYearTrsansaction();
        renderChart();
	}
	
	/**
	 * 显示图表
	 */
	private void renderChart() {
		
		countMonthSpendToMap();
		
		String[] titles = new String[] { dateStart.substring(0, 4) + "年每月消费"};
		List<double[]> x = new ArrayList<double[]>();
		x.add(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
		
		List<double[]> values = new ArrayList<double[]>();
		values.add(extractShowTransactionTotalMonthSpendArray());
		
		int[] colors = new int[] { Color.BLUE};
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE};
		
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++) {
			((XYSeriesRenderer) renderer.getSeriesRendererAt(i))
					.setFillPoints(true);
		}
		double yMax = getTheYMax();
		setChartSettings(renderer, dateStart.substring(0, 4) + "每月消费统计", "月份",
				"单位/元", 1, 12, 0, yMax, Color.BLACK, Color.BLACK);
		renderer.setXLabels(12);
		renderer.setYLabels(10);
		renderer.setShowGrid(true);
		renderer.setXLabelsAlign(Align.RIGHT);
		renderer.setYLabelsAlign(Align.RIGHT);
		renderer.setPanLimits(new double[] { 1, 12, 0, yMax });
		renderer.setZoomLimits(new double[] { 1, 12, 0, yMax });
		renderer.setMarginsColor(Color.LTGRAY);
		renderer.setBackgroundColor(Color.WHITE);

		View lineChartView = ChartFactory.getLineChartView(this, buildDataset(
				titles, x, values), renderer);
		LinearLayout chartsLayout = (LinearLayout)findViewById(R.id.chart_layout);
		chartsLayout.removeAllViews();
		chartsLayout.addView(lineChartView);
	}
	
	/**
	 * 初始化显示的数据
	 * @param inputShowTransactionList
	 * @param inputTotalTransactionList
	 */
	public static void countDaySpendToMap() {
		showDaySpendMap.clear();
		for (MyTransaction transaction : showTransactionList) {
			if (transaction.getiSum().startsWith("+")) {
				continue;
			}
			if (showDaySpendMap.get(transaction.getdDate()) == null) {
				showDaySpendMap.put(transaction.getdDate(), new  BigDecimal(transaction.getiSum()));
			} else {
				BigDecimal tempCount = showDaySpendMap.get(transaction.getdDate());
				showDaySpendMap.put(transaction.getdDate(), tempCount.add(new BigDecimal(transaction.getiSum())));
			}
		}
	}
	
	/**
	 * 初始化数据
	 * @param inputTotalTransactionList
	 */
	public static void initData(List<MyTransaction> inputTotalTransactionList) {
		totalTransactionList = inputTotalTransactionList;
	}
	
	/**
	 * 统计每天总共花费
	 * @return
	 */
	private double[] extractShowTransactionTotalDateSpendArray() {
		String currentDate = dateStart;
		int maxDay = DateUtil.getMaxDay(currentDate.substring(0, 4), currentDate.substring(5, 7));
		double[] spendArray = new double[maxDay];
		for (int i = 0; i < maxDay; i ++) {
			String tempDate = currentDate.substring(0, currentDate.length()-2) + (i > 10 ? i : "0"+i);
			if (showDaySpendMap.get(tempDate) != null) {
				spendArray[i] = showDaySpendMap.get(tempDate).divide(new BigDecimal("100")).multiply(new BigDecimal("-1")).doubleValue();
			} else {
				spendArray[i] = 0;
			}
		}
		return spendArray;
	}
	
	/**
	 * 计算每月消费
	 * @return
	 */
	private void countMonthSpendToMap() {
		rangeTransactionByMonth();
		
		showMonthSpendMap.clear();
		for (MyTransaction transaction : showTransactionList) {
			if (transaction.getiSum().startsWith("+")) {
				continue;
			}
			String currentMonth = transaction.getdDate().substring(0, 7);
			if (showMonthSpendMap.get(currentMonth) == null) {
				showMonthSpendMap.put(currentMonth, new  BigDecimal(transaction.getiSum()));
			} else {
				BigDecimal tempCount = showMonthSpendMap.get(currentMonth);
				showMonthSpendMap.put(currentMonth, tempCount.add(new BigDecimal(transaction.getiSum())));
			}
		}
	}
	
	/**
	 * 统计每月总共花费
	 * @return
	 */
	private double[] extractShowTransactionTotalMonthSpendArray() {
		String currentYear = dateStart;
		int maxMonth = 12;
		double[] spendArray = new double[maxMonth];
		for (int i = 0; i < maxMonth; i ++) {
			String tempDate = currentYear.substring(0, 4) + "-" + (i >= 9 ? (i+1) : "0"+(i+1));
			if (showMonthSpendMap.get(tempDate) != null) {
				spendArray[i] = showMonthSpendMap.get(tempDate).divide(new BigDecimal("100")).multiply(new BigDecimal("-1")).doubleValue();
			} else {
				spendArray[i] = 0;
			}
		}
		
		return spendArray;
	}
	
	/**
	 * 按月进行归类
	 */
	private void rangeTransactionByMonth() {
		List<MyTransaction> transactionList;
		for (MyTransaction myTransaction : totalTransactionList) {
			String tdDate = myTransaction.getdDate();
			if (StringUtils.isNULL(tdDate) || tdDate.length() < 7) continue;
				transactionList = showTransactionByMonthMap.get(tdDate.substring(0, 7));
			if (transactionList == null) {
				transactionList = new ArrayList<MyTransaction>();
			}
			transactionList.add(myTransaction);
			showTransactionByMonthMap.put(tdDate.substring(0, 7), transactionList);
		}
	}
	
	
	/**
	 * 定义Y轴最大值
	 * @param inputMap
	 * @return
	 */
	private double getTheYMax() {
		BigDecimal maxValue = BigDecimal.ZERO;
		for (String key : showMonthSpendMap.keySet()) {
			if (maxValue.compareTo(showMonthSpendMap.get(key).abs()) < 0) {
				maxValue = showMonthSpendMap.get(key).abs();
			}
		}
		int maxValueInt = maxValue.intValue()/100;//单位换成元
		maxValueInt = (maxValueInt/1000 + 1)*1000;
		return maxValueInt;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.preMonth: {
			showTransactionList = getPreYearTrsansaction();
			
			renderChart();
			nextMonth.setEnabled(true);
			break;
		}
		case R.id.currentMonth: {
			showTransactionList = getCurrentYearTrsansaction();
			renderChart();
			nextMonth.setEnabled(false);
			break;
		}
		case R.id.nextMonth: {
			showTransactionList = getNextYearTrsansaction();
			renderChart();
			//如果没有下个月记录，设置不可点击
			if(!hasNextMonth()) {
				nextMonth.setEnabled(false);
			}
			break;
		}
		}
	}
	
	/**
	 * 找当前年的记录
	 * @return
	 */
	private List<MyTransaction> getCurrentYearTrsansaction() {
		String currentDate = DateUtil.getDate();
		String currentYearFirstDate = currentDate.substring(0, 4) + "-01-01";
		String currentYearMaxDate = currentDate.substring(0, 4) + "-12-31";
		dateStart = currentYearFirstDate;
		dateEnd = currentYearMaxDate;
		return findTransactionByYear(currentYearFirstDate, currentYearMaxDate);
	}
	
	/**
	 * 查找上一年的记录
	 * @return
	 */
	private List<MyTransaction> getPreYearTrsansaction() {
		String preMonthDate = DateUtil.addYear(dateStart, -1);
		
		String searchYearFirstDate = preMonthDate.substring(0, 4) + "-01-01";
		String searchYearMaxDate = preMonthDate.substring(0, 4) + "-12-31";
		dateStart = searchYearFirstDate;
		dateEnd = searchYearMaxDate;
		return findTransactionByYear(searchYearFirstDate, searchYearMaxDate);
	}
	
	/**
	 * 查找下一年的记录
	 * @return
	 */
	private List<MyTransaction> getNextYearTrsansaction() {
		String nextMonthDate = DateUtil.addYear(dateStart, 1);
		
		String searchYearFirstDate = nextMonthDate.substring(0, 4) + "-01-01";
		String searchYearMaxDate = nextMonthDate.substring(0, 4) + "-12-31";
		dateStart = searchYearFirstDate;
		dateEnd = searchYearMaxDate;
		return findTransactionByYear(searchYearFirstDate, searchYearMaxDate);
	}
	
	/**
	 * 是否是最后一个月
	 * @return
	 */
	private boolean hasNextMonth() {
		String currentDate = DateUtil.getDate();
		
		String nextMonthDate = DateUtil.addYear(dateStart, 1);
		if (currentDate.compareTo(nextMonthDate) < 0) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 查找两个日期之间的记录
	 * @return
	 */
	private List<MyTransaction> findTransactionByYear(String dateFrom, String dateTo) {
		List<MyTransaction> transactions = new ArrayList<MyTransaction>();
		
		for (MyTransaction transaction : totalTransactionList) {
			if (!StringUtils.isNULL(transaction.getdDate())) {
				if ((transaction.getdDate().compareTo(dateFrom) > 0 || transaction.getdDate().compareTo(dateFrom) == 0) 
						&& transaction.getdDate().compareTo(dateTo) < 0 || transaction.getdDate().compareTo(dateTo) == 0) {
					transactions.add(transaction);
				}
			}
		}
		
		return transactions;
	}

}



